package com.dgut.czqqq.exp03.service;

import com.dgut.czqqq.exp03.contains.ExpContains;
import com.dgut.czqqq.exp03.pojo.DataVo;
import com.dgut.czqqq.exp03.pojo.VirusData;
import com.google.gson.Gson;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.xml.crypto.Data;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;


@Service
public class CsvServiceImpl implements CsvService, InitializingBean {

/**
 * 日志变量log
 */
private static final Logger log = LoggerFactory.getLogger(CsvServiceImpl.class);

    @Override
    @Scheduled(cron = "0 0 6 * * *")//每日早上六点更新data.csv文件内容
    public void getInputStream() {
        RequestEntity<Void> requestEntity =
                org.springframework.http.RequestEntity
                        .get(ExpContains.COVID_19_GETURI)
                        .headers(httpHeaders -> httpHeaders.add(ExpContains.HEADER_NAME,ExpContains.HEADER_VALUE))
                        .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();
        getCsv(body);
    }

    @Override
    public void getCsv(Resource body) {
        try {
            InputStream inputStream = body.getInputStream();
            OutputStream outputStream = new FileOutputStream("data.csv");

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len=inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public VirusData getDetailData(CSVRecord record) {
        String provinceName = record.get("Province/State");//获取省份/州名
        String countryName = record.get("Country/Region");//获取国家/地区名
        Integer totalNum = Integer.valueOf(record.get(record.size() - 1));// 获取确诊总数
        Integer AddNum = totalNum - Integer.valueOf(record.get(record.size() - 2));//获取新增确诊数
        if(AddNum < 0){
            AddNum = 0;
        }
        VirusData data = new VirusData(provinceName,countryName,totalNum,AddNum);
        return data;
    }

    @Override
    public DataVo getDataVo(List<VirusData> list) {
        Integer globalConfirmedNum = 0;
        Integer addConfirmedNum = 0;
        for(VirusData item : list){
            globalConfirmedNum += item.getNowTotalNum();
            addConfirmedNum += item.getAddNum();
        }
        DataVo dataVo = new DataVo(list,globalConfirmedNum,addConfirmedNum);
        return dataVo;
    }


    @Override
    public String resolveCsvGetGlobalNum() throws IOException {
        Reader in = new FileReader("data.csv");
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
        List<VirusData> list = new ArrayList<VirusData>();
        Gson gson = new Gson();
        for (CSVRecord record : records) {
            VirusData data = getDetailData(record);
            list.add(data);
        }
        DataVo dataVo = getDataVo(list);
        return gson.toJson(dataVo);
    }
    @Override
    public String resolveCsvGetOneCountryNum(String searchCoutryName) throws IOException {
        Reader in = new FileReader("data.csv");
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
        List<VirusData> list = new ArrayList<VirusData>();
        Integer globalConfirmedNum = 0;
        Integer addConfirmedNum = 0;
        Gson gson = new Gson();
        for (CSVRecord record : records) {
            VirusData data = getDetailData(record);
            if(!StringUtils.equals(searchCoutryName,data.getCountry())){
                continue;
            }
            list.add(data);
        }
        DataVo dataVo = getDataVo(list);
        return gson.toJson(dataVo);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        getInputStream();
    }
}
